package com.leyou.gateway.filters;

import com.leyou.common.auth.entity.Payload;
import com.leyou.common.auth.entity.UserInfo;
import com.leyou.common.auth.utils.JwtUtils;
import com.leyou.common.utils.CookieUtils;
import com.leyou.gateway.config.JwtProperties;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * @author Eric
 * @version v1.0
 * @package com.leyou.gateway.filters
 * @date 2019/7/8 16:58
 * @description:
 **/
@Slf4j
@Component
public class AuthFilter extends ZuulFilter {


    private JwtProperties jwtProperties;

    public AuthFilter(JwtProperties jwtProperties) {
        this.jwtProperties = jwtProperties;
    }

    @Autowired
    private FilterProperties filterProperties;


    @Override
    public String filterType() {
        return FilterConstants.PRE_TYPE;
    }

    @Override
    public int filterOrder() {
        return FilterConstants.FORM_BODY_WRAPPER_FILTER_ORDER - 1;
    }

    @Override
    public boolean shouldFilter() {

        //获取上下文
        RequestContext context = RequestContext.getCurrentContext();
        //获取request
        HttpServletRequest request = context.getRequest();

        //获取请求的路径
        String requestURI = request.getRequestURI();

        return isAllowPath(requestURI);
    }

    private boolean isAllowPath(String requestURI) {
        List<String> allowPaths = filterProperties.getAllowPaths();
        boolean flag =true;
        for (String allowPath : allowPaths) {
            if (requestURI.startsWith(allowPath)){
                flag=false;
                break;
            }
        }
        return flag;
    }

    @Override
    public Object run(){

        //获取上下文
        RequestContext context = RequestContext.getCurrentContext();
        //获取request
        HttpServletRequest request = context.getRequest();
        //获取Token
        String token = CookieUtils.getCookieValue(request, jwtProperties.getUser().getCookieName());
        try {
            //解析Token
            Payload<UserInfo> payload = JwtUtils.getInfoFromToken(token, jwtProperties.getPublicKey(), UserInfo.class);
            //获得用户角色信息
            UserInfo user = payload.getUserInfo();
            String role = user.getRole();
            //获取当前资源路径
            String method = request.getMethod();
            String path = request.getRequestURI();
            // TODO 判断权限，此处暂时空置，等待权限服务完成后补充
            log.info("【网关】用户{},角色{}。访问服务{} : {}，", user.getUsername(), role, method, path);
        } catch (Exception e) {

            // 校验出现异常，返回403
            context.setSendZuulResponse(false);
            context.setResponseStatusCode(403);
            log.error("注意非法登录！地址来源是{}",request.getRemoteHost(),e);
        }
        return null;
    }
}
